using WebSelfHost.Utility.Core;
using WebSelfHost.Utility.Extension;
using WebSelfHost.Utility.Logs;
using JinianNet.JNTemplate;
using Microsoft.AspNetCore;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;

using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using System.Net;
using System.Net.Sockets;
using WebSelfHost.Logic.Base;
using WebSelfHost.Logic.Sys;
using System.Security;
using WebSelfHost.Logic;


#if NETFRAMEWORK
using System.Web.Http;
using Swashbuckle.Application;
using System.Net.Http.Formatting;
using System.ServiceModel;
using System.ServiceModel.Description;
using System.Web;
using System.Web.SessionState;
using Microsoft.Owin.Hosting;
#else
using Microsoft.AspNetCore.Hosting;
#endif

namespace WebSelfHost.Web
{
    public class Worker : BackgroundService
    {
        public Worker()
        {
        }

        public override Task StartAsync(CancellationToken cancellationToken)
        {
            Start();
            return base.StartAsync(cancellationToken);
        }

        public override Task StopAsync(CancellationToken cancellationToken)
        {
            Stop();
            return base.StopAsync(cancellationToken);
        }

        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {

            while (!stoppingToken.IsCancellationRequested)
            {
                await Task.Delay(1, stoppingToken);
            }
        }



        /// <summary>
        /// 停止服务
        /// </summary>
        private void Stop()
        {
            LogHelper.Info("正在停止Web服务");
#if !NETFRAMEWORK
            host.StopAsync();
#else
            host.Dispose();
#endif 
        }


        /// <summary>
        /// 开启服务
        /// </summary>
        public void Start()
        {
            //配置文件读取
            GlobalValue.Config = File.ReadAllText(MyEnvironment.RootPath("Configs/config.json")).ToObject<Configs>();
            BaseLogic.MySQLConnString = GlobalValue.Config.DBConnectStr;
            BaseLogic.IsDebug = GlobalValue.Config.Debug;
            //日志配置
            var template = Engine.LoadTemplate(MyEnvironment.RootPath("Configs/log4net.config"));
            template.Set("LogBasePath", GlobalValue.Config.LogBasePath);
            template.Set("InfoLogPath", GlobalValue.Config.InfoLogPath);
            template.Set("ErrorLogPath", GlobalValue.Config.ErrorLogPath);
            template.Set("OperateLogPath", GlobalValue.Config.OperateLogPath);
            var result = template.Render();
            LogHelper.Init(result);
            StartWebServer();    //开启web服务 
        }


#if !NETFRAMEWORK
        private IWebHost host;
#else
        private IDisposable host;
#endif
        public void StartWebServer()
        {
            LogHelper.Info("正在开启Web服务");
            //这句不加，在Linux下使用图形操作会报错
            AppContext.SetSwitch("System.Drawing.EnableUnixSupport", true);
#if !NETFRAMEWORK
            //启动Web服务
            host = WebHost.CreateDefaultBuilder(new string[] { })
                .ConfigureLogging(logging =>
                {
                    logging.ClearProviders();
                    if (GlobalValue.Config.Debug)
                        logging.AddConsole();
                })
                .UseUrls($"http://*:{GlobalValue.Config.HttpPort}")
                .UseContentRoot(MyEnvironment.RootPath(""))
                .UseWebRoot(MyEnvironment.RootPath("wwwroot"))
                .UseKestrel(options =>
                {
                    options.Limits.MaxRequestBodySize = null;
                })
                .UseStartup<Startup>().Build();
            host.RunAsync();
#else

            StartOptions startOptions = new StartOptions();
            //string name = Dns.GetHostName();
            //IPAddress[] ipadrlist = Dns.GetHostAddresses(name);
            //foreach (IPAddress ip in ipadrlist)
            //{
            //    if (ip.AddressFamily == AddressFamily.InterNetwork)
            //    {
            //        string baseAddress = $"http://{ip}:{GlobalValue.Config.HttpPort}/";
            //        startOptions.Urls.Add(baseAddress);
            //    }
            //}
            //startOptions.Urls.Add($"http://localhost:{GlobalValue.Config.HttpPort}/");
            //startOptions.Urls.Add($"http://127.0.0.1:{GlobalValue.Config.HttpPort}/");
            startOptions.Urls.Add($"http://*:{GlobalValue.Config.HttpPort}/");
            host = WebApp.Start<Startup>(startOptions);

#endif
        }
    }
}
